<template>
    <view class="container">
        <view class="box">
            <!-- 选项卡切换 -->
            <view class="tab">
                <span @click="activeTab = 'login'" :class="{ active: activeTab === 'login' }">登录</span>
                <span @click="activeTab = 'register'" :class="{ active: activeTab === 'register' }">注册</span>
            </view>
            <!-- 登录表单 -->
            <form v-if="activeTab === 'login'" @submit.prevent="login">
                <label>手机号</label>
                <input v-model="loginUsername" type="text" placeholder="手机号">
                <label>密码</label>
                <input v-model="loginPassword" type="password" placeholder="密码">
                <button type="button" @click="loginAction">登录</button>
            </form>
            <!-- 注册表单 -->
            <template v-if="activeTab === 'register'">
                <template v-if="!isBrowserRegistered">
                    <form @submit.prevent="register">
                        <label>手机号</label>
                        <input v-model="registerUsername" type="text" placeholder="手机号">
                        <label>用户昵称</label>
                        <input v-model="registerNickname" type="text" placeholder="用户昵称">
                        <label>密码</label>
                        <input v-model="registerPassword" type="password" placeholder="密码">
                        <button type="button" @click="registerAction">注册</button>
                    </form>
                </template>
                <template v-else>
                    <view class="browser-registered-warning">
                        <text>已注册过账号，请直接登录</text>
                    </view>
                </template>
            </template>
        </view>
        <uni-popup ref="popup" type="message">
            <uni-popup-message type="error" :message="errorMsg" class="error-text"></uni-popup-message>
        </uni-popup>
    </view>
</template>

<script>
import { userLogin } from '@/api/login.js';

export default {
    data() {
        return {
            errorMsg: "",
            activeTab: 'login',
            // 分离登录和注册的表单数据
            loginUsername: '',
            loginPassword: '',
            registerUsername: '',
            registerPassword: '',
            registerNickname: '',
            isBrowserRegistered: false // 浏览器注册状态
        };
    },
    onShow() {
        this.checkBrowserRegistration();
        uni.removeStorageSync('token');
        uni.removeStorageSync('userInfo');
    },
    methods: {
        // 检查浏览器注册状态
        checkBrowserRegistration() {
            try {
                const registered = uni.getStorageSync('browserRegistered');
                this.isBrowserRegistered = !!registered;
                
                if (this.isBrowserRegistered) {
                    this.activeTab = 'login';
                }
            } catch (e) {
                console.error('获取浏览器注册状态失败', e);
            }
        },
        
        // 验证手机号是否合法
        validatePhoneNumber(phone) {
            const reg = /^1[3-9]\d{9}$/;
            return reg.test(phone);
        },
        
        loginAction() {
            if (this.loginUsername === "") {
                this.errorMsg = "请输入手机号";
                this.$refs.popup.open('top');
                return;
            }
            if (!this.validatePhoneNumber(this.loginUsername)) {
                this.errorMsg = "请输入有效的手机号";
                this.$refs.popup.open('top');
                return;
            }
            
            let data = {
                "action": "login",
                "username": this.loginUsername,
                "password": this.loginPassword
            };
            
            userLogin(data).then((res) => {
                if (res.code === 200) {
                    uni.setStorageSync("token", res.data.token);
                    uni.setStorageSync("userInfo", res.data);
                    uni.switchTab({
                        url: "/pages/index/index"
                    });
                } else {
                    this.errorMsg = res.msg || "登录失败";
                    this.$refs.popup.open('top');
                }
            }).catch(err => {
                this.errorMsg = "登录请求失败";
                this.$refs.popup.open('top');
            });
        },
        
        registerAction() {
            // 检查浏览器是否已注册
            if (this.isBrowserRegistered) {
                this.errorMsg = "当前浏览器已注册过账号";
                this.$refs.popup.open('top');
                return;
            }
            
            if (this.registerUsername === "") {
                this.errorMsg = "请输入手机号";
                this.$refs.popup.open('top');
                return;
            }
            
            if (!this.validatePhoneNumber(this.registerUsername)) {
                this.errorMsg = "请输入有效的手机号";
                this.$refs.popup.open('top');
                return;
            }
            
            if (!this.registerNickname) {
                this.registerNickname = this.registerUsername;
            }
            
            let data = {
                "action": "register",
                "username": this.registerUsername,
                "password": this.registerPassword,
                "nickname": this.registerNickname,
                "userType": '1'
            };
            
            userLogin(data).then((res) => {
                if (res.code === 11012) {
                    try {
                        // 设置浏览器注册状态
                        uni.setStorageSync('browserRegistered', 'true');
                        this.isBrowserRegistered = true;
                    } catch (e) {
                        console.error('设置浏览器注册状态失败', e);
                    }
                    
                    uni.setStorageSync("token", res.data.token);
                    uni.setStorageSync("userInfo", res.data);
                    
                    uni.switchTab({
                        url: "/pages/index/index"
                    });
                } else {
                    this.errorMsg = res.msg || "注册失败";
                    this.$refs.popup.open('top');
                }
            }).catch(err => {
                this.errorMsg = "注册请求失败";
                this.$refs.popup.open('top');
            });
        },
        
        login() {
            this.loginAction();
        },
        register() {
            this.registerAction();
        }
    }
};
</script>

<style scoped>
/* 全局样式 */
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f4f4f9;
    background-image: url('https://ai-public.mastergo.com/ai/img_res/38644480179cfe7f528c88e0e54611f2.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    padding: 0 20px;
}

.box {
    width: 100%;
    max-width: 380px;
    background-color: rgba(255, 255, 255, 0.6);
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.box {
    color: #333;
    font-weight: bold;
}

.tab {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
}

.tab span {
    padding: 10px 20px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: border-bottom 0.3s ease;
}

.tab span.active {
    border-bottom: 2px solid #34495e;
    color: #34495e;
}

form {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

label {
    font-size: 14px;
    color: #555;
}

input {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 14px;
    transition: border-color 0.3s ease;
}

input:focus {
    outline: none;
    border-color: #34495e;
}

button {
    margin-top: 5px;
    padding: 12px;
    background-color: #34495e;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
}

@media screen and (min-width: 1300px) {
    .live-card {
        width: 80%;
        height: 400px;
    }
}

button:hover {
    background-color: #2c3e50;
}

.error-text {
    color: #f56c6c;
    text-align: center;
}

/* 浏览器已注册警告样式 */
.browser-registered-warning {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background-color: #fef0f0;
    border-radius: 8px;
    color: #f56c6c;
    text-align: center;
    border: 1px solid #fbc4c4;
    font-size: 16px;
}
</style>